<?php

class LinksController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','url','curl'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','comment'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Links;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Links']))
		{
			$model->attributes=$_POST['Links'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->link_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Links']))
		{
			$model->attributes=$_POST['Links'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->link_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Links');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Links('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Links']))
			$model->attributes=$_GET['Links'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Links::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='links-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionCurl(){
		$model = new Links('getContent');
		if(Yii::app()->user->isGuest){
			Yii::app()->user->loginRequired();
			Yii::app()->end();
		}

		if(isset($_POST['ajax']) && $_POST['ajax']==='links-form')
		{
			$val_res =  CActiveForm::validate($model);
			$erar = json_decode($val_res);
			if(!empty($erar)){
				NC::json(false,$val_res);
				Yii::app()->end();
			}
		}
		
		//$_GET['link'] = urlencode('http://www.qq.com');
		//查找是否已分享过
		$link_url = isset($_POST['Links']['link_url']) ? $_POST['Links']['link_url'] : $_GET['link'];
		//dbg($link_url,true);
		$validateUrlUnique = News::validateUrlUnique($link_url);
		if($validateUrlUnique !== null){
			$comment = new Comments;
			echo $this->render('_exist',array('boxSeriaModel'=>$validateUrlUnique,'comment'=>$comment));
			//echo '该网址已经存在';
			Yii::app()->end();
		}
		$curl = new Curl();
		$crawl = $curl->getData($link_url);
		//dbg($crawl['title']);
		/*if($crawl['title'] == ''){
			$crawl['title'] = $_GET['title'];
		}
		if($crawl['description'] == ''){
			$crawl['description'] = $_GET['desc'];
		}*/
		$crawl['plugin'] = false;
		if(isset($_GET['link'])){
			$crawl['plugin'] = true;//是否是插件请求
		}
		//dbg($crawl);
		if($crawl['success']){
			if(!empty($crawl['keyword'])){
				$keyword = $crawl['keyword'];
			}else{
				$keyword = $crawl['title'];
			}
			$rawurl = $this->rawurl($keyword,$crawl['description']);
			$boxSeriaModel = new News;
			echo $this->render('_crawl',array('crawl'=>$crawl,'tag'=>$rawurl,'boxSeriaModel'=>$boxSeriaModel));
		}else{
			NC::json(false,$crawl['error']);
		}
		
	}
	protected function rawurl($subject,$content){
		$subjectenc = rawurlencode(strip_tags($subject));
		$messageenc = rawurlencode(strip_tags(preg_replace("/\[.+?\]/U", '', $content)));
		$data = @implode('', file("http://keyword.discuz.com/related_kw.html?title=$subjectenc&content=$messageenc&ics=utf-8&ocs=utf-8"));
		$kws = array();
		if($data) {
			$parser = xml_parser_create();
			xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
			xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
			xml_parse_into_struct($parser, $data, $values, $index);
			xml_parser_free($parser);
			foreach($values as $valuearray) {
				if($valuearray['tag'] == 'kw' || $valuearray['tag'] == 'ekw') {
						$kws[] = trim($valuearray['value']);
				}
			}			
		}
		return array_slice($kws,0,4);
	}
	public function actionComment(){
		//自动顶，并加入评论
		$newsID = (int)NC::_p("news_id",0);
		if(!$newsID)
			throw new CHttpException('400','无效的请求！');
		//评论
		$comment = new Comments;
		if(isset($_POST['Comments'])){
			$comment->attributes = $_POST['Comments'];
			$comment->news_id = $newsID;
			$comment->comment_time = time();
			$comment->user_id = Yii::app()->user->id;
			$comment->user_name = Yii::app()->user->name;
			if($comment->save()){
				//更新评论数
				News::model()->updateCounters(array('comment_num'=>1),'news_id=:news_id',array(':news_id'=>$newsID));
				User::model()->updateCounters(array('comment_num'=>1),'user_id=:user_id',array(':user_id'=>$comment->user_id));
			}
		}
		//顶
		$actions = Actions::model()->exists('news_id=:news_id and user_id=:user_id',array(':news_id'=>$newsID,':user_id'=>Yii::app()->user->id));
		if(!$actions){
			if(Actions::addActions($newsID,'digg')){
				//更新nc_news表
				News::model()->updateCounters(array('digg_num'=>1),'news_id=:news_id',array(':news_id'=>$newsID));
				//更新用户表
				User::model()->updateCounters(array('share_num'=>1),'user_id=:user_id',array(':user_id'=>Yii::app()->user->id));
			}
		}
		$this->redirect('/news/'.$newsID);
		//
	}
}
